{% extends "base.html" %}

{% block title %}
{% if search_query %}搜索 "{{ search_query }}" - 城会玩{% else %}城会玩 - 本地兴趣活动共享平台{% endif %}
{% endblock %}

{% block style %}
{{ block.super }}
/* 地图相关样式 - 优化加载状态 */
.map-marker-popup {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.map-marker-popup h6 {
    font-size: 0.9rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.map-marker-popup .small {
    font-size: 0.8rem;
}

.map-marker-popup .btn {
    font-size: 0.8rem;
    padding: 0.25rem 0.5rem;
}

#nearby-activities-list .list-group-item.active {
    background-color: var(--primary);
    border-color: var(--primary);
    color: white;
}

#nearby-activities-list .list-group-item.active .badge {
    background-color: white;
    color: var(--primary);
}

#nearby-activities-list .list-group-item.active .text-muted {
    color: rgba(255, 255, 255, 0.8) !important;
}

@media (max-width: 768px) {
    #map-container {
        height: 300px;
    }
}

.map-controls {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    display: flex;
    gap: 5px;
}

.map-controls .btn {
    box-shadow: 0 2px 6px rgba(0,0,0,0.3);
    background: white;
    border: 1px solid #ddd;
}

.map-controls .btn:hover {
    background: var(--primary);
    color: white;
}

.location-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(255,255,255,0.95);
    padding: 15px 20px;
    border-radius: 10px;
    text-align: center;
    z-index: 1000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    border: 1px solid #e9ecef;
    min-width: 200px;
}

.location-loading .loading-text {
    font-size: 14px;
    margin-top: 8px;
    color: #495057;
}

.map-error {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: #f8f9fa;
    border-radius: 10px;
}

/* 快速加载状态 */
.map-quick-loading {
    background: white;
    padding: 10px 15px;
    border-radius: 8px;
    font-size: 14px;
    color: #495057;
}

/* 其他原有样式保持不变 */
.hero-section {
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.9) 0%, rgba(78, 205, 196, 0.8) 100%), url(https://images.unsplash.com/photo-1511795409834-ef04bbd61622?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80);
    background-size: cover;
    background-position: center;
    color: white;
    padding: 100px 0;
    text-align: center;
    border-radius: 0 0 30px 30px;
    margin-top: -20px;
}

.section-title {
    position: relative;
    margin-bottom: 2rem;
    padding-bottom: 0.5rem;
}

.section-title:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 60px;
    height: 3px;
    background-color: var(--primary);
}

.activity-card {
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    margin-bottom: 1.5rem;
    background: white;
}

.activity-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.15);
}

.activity-image {
    height: 180px;
    background-size: cover;
    background-position: center;
    position: relative;
}

.activity-category {
    position: absolute;
    top: 10px;
    left: 10px;
    background: var(--primary);
    color: white;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.activity-status {
    position: absolute;
    top: 10px;
    right: 10px;
    background: var(--secondary);
    color: white;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.8rem;
}

.activity-full {
    background: #dc3545;
}

.activity-details {
    padding: 1.5rem;
}

.activity-title {
    font-weight: 600;
    margin-bottom: 0.5rem;
    font-size: 1.1rem;
}

.activity-meta {
    display: flex;
    justify-content: space-between;
    color: #6c757d;
    font-size: 0.9rem;
    margin-bottom: 1rem;
}

.activity-participants {
    display: flex;
    align-items: center;
}

.avatar-group {
    display: flex;
    margin-right: 10px;
}

.avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 2px solid white;
    margin-left: -10px;
    background-color: #e9ecef;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    font-weight: bold;
    color: #6c757d;
}

.avatar:first-child {
    margin-left: 0;
}

.map-container {
    height: 400px;
    background-color: #e9ecef;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
}

.feature-icon {
    width: 60px;
    height: 60px;
    background: var(--primary);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1rem;
    color: white;
    font-size: 1.5rem;
}

.search-suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    z-index: 1000;
    max-height: 300px;
    overflow-y: auto;
    display: none;
}

.search-suggestion-item {
    padding: 10px 15px;
    border-bottom: 1px solid #f8f9fa;
    cursor: pointer;
    transition: background-color 0.2s;
}

.search-suggestion-item:hover {
    background-color: #f8f9fa;
}

.search-suggestion-item:last-child {
    border-bottom: none;
}

.search-suggestion-highlight {
    color: var(--primary);
    font-weight: 600;
}

.search-container {
    position: relative;
}

.search-results-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
}

.search-results-count {
    color: #6c757d;
    font-size: 0.9rem;
}

@media (max-width: 768px) {
    .hero-section {
        padding: 80px 0 60px 0;
    }

    .hero-section h1 {
        font-size: 2rem;
    }

    .search-suggestions {
        position: fixed;
        top: auto;
        left: 15px;
        right: 15px;
        max-height: 200px;
    }
}
{% endblock %}

{% block content %}
    {% include "nav.html" %}
<!-- 英雄区域 -->
<section class="hero-section">
    <div class="container">
        <h1 class="display-4 fw-bold mb-4">
            {% if search_query %}
            搜索 "{{ search_query }}"
            {% else %}
            发现身边的精彩活动
            {% endif %}
        </h1>
        <p class="lead mb-4">
            {% if search_query %}
            找到 {{ recommended_activities|length }} 个相关活动
            {% else %}
            探索本地兴趣活动，结识志同道合的朋友，丰富你的社交生活
            {% endif %}
        </p>
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="search-container">
                    <form method="get" action="{% url 'index' %}" id="searchForm">
                        <div class="input-group input-group-lg">
                            <input type="text" class="form-control" name="search" id="searchInput"
                                   placeholder="搜索活动、地点、分类或组织者..."
                                   value="{{ search_query }}"
                                   autocomplete="off">
                            <button class="btn btn-primary" type="submit">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                        </div>
                    </form>
                    <div class="search-suggestions" id="searchSuggestions">
                        <!-- 搜索建议将在这里动态显示 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 推荐活动/搜索结果 -->
<section class="py-5">
    <div class="container">
        <div class="search-results-header">
            <h2 class="section-title mb-0">
                {% if search_query %}
                搜索结果
                {% else %}
                推荐活动
                {% endif %}
            </h2>
            {% if not search_query %}
            <a href="/meet/active/" class="btn btn-outline-primary">查看全部</a>
            {% endif %}
        </div>

        {% if search_query %}
        <div class="search-results-count mb-4">
            找到 {{ recommended_activities|length }} 个与 "{{ search_query }}" 相关的活动
            {% if recommended_activities|length == 0 %}
            <a href="{% url 'index' %}" class="btn btn-outline-secondary btn-sm ms-2">返回首页</a>
            {% endif %}
        </div>
        {% endif %}

        <div class="row">
            {% for activity in recommended_activities %}
            <div class="col-md-6 col-lg-4">
                <div class="activity-card">
                    <div class="activity-image" style="background-image: url('{{ activity.image.url }}')">
                        <div class="activity-category">{{ activity.category.name }}</div>
                        <div class="activity-status {% if activity.is_full %}activity-full{% endif %}">
                            {% if activity.is_full %}已满员{% else %}进行中{% endif %}
                        </div>
                    </div>
                    <div class="activity-details">
                        <h3 class="activity-title">
                            <a href="{% url 'active_detail' activity.id %}" class="text-decoration-none text-dark">
                                {{ activity.title }}
                            </a>
                        </h3>
                        <div class="activity-meta">
                            <span><i class="far fa-calendar-alt me-1"></i> {{ activity.start_time|date:"m月d日 H:i" }}</span>
                            <span><i class="fas fa-map-marker-alt me-1"></i> {{ activity.location_name }}</span>
                        </div>
                        <p class="text-muted small">{{ activity.description|truncatechars:60 }}</p>
                        <div class="activity-participants">
                            <div class="avatar-group">
                                <!-- 使用默认头像图标 -->
                                <div class="avatar" style="background-color: #FF6B35; color: white;">
                                    <i class="fas fa-user"></i>
                                </div>
                            </div>
                            <span class="small text-muted">{{ activity.current_participants }}/{{ activity.max_participants }}人</span>
                        </div>
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="col-12 text-center">
                {% if search_query %}
                <div class="py-5">
                    <i class="fas fa-search fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">没有找到与 "{{ search_query }}" 相关的活动</h4>
                    <p class="text-muted">尝试使用其他关键词搜索，或者浏览所有活动</p>
                    <a href="{% url 'index' %}" class="btn btn-primary">返回首页</a>
                    <a href="{% url 'active' %}" class="btn btn-outline-primary ms-2">查看所有活动</a>
                </div>
                {% else %}
                <p class="text-muted">暂无推荐活动</p>
                {% endif %}
            </div>
            {% endfor %}
        </div>
    </div>
</section>

<!-- 地图和附近活动 -->
<section class="py-5 bg-light">
    <div class="container">
        <h2 class="section-title">
            {% if search_query %}
            相关活动位置
            {% else %}
            附近活动
            {% endif %}
        </h2>
        <div class="row">
            <div class="col-lg-8 mb-4 mb-lg-0">
                <div id="map-container" class="map-container">
                    <!-- 地图将在这里渲染 -->
                    <div class="d-flex align-items-center justify-content-center h-100 bg-secondary text-white">
                        <div class="text-center">
                            <i class="fas fa-map-marked-alt fa-3x mb-3"></i>
                            <p>地图加载中...</p>
                            <small>如果地图长时间未加载，请检查网络连接</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="list-group" id="nearby-activities-list">
                    {% for activity in nearby_activities %}
                    <a href="{% url 'active_detail' activity.id %}"
                       class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
                       data-activity-id="{{ activity.id }}"
                       data-lat="{{ activity.latitude|default:0 }}"
                       data-lng="{{ activity.longitude|default:0 }}">
                        <div>
                            <h6 class="mb-1">{{ activity.title }}</h6>
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt me-1"></i>
                                {{ activity.location_name }} ·
                                {{ activity.start_time|date:"m月d日 H:i" }}
                            </small>
                        </div>
                        <span class="badge bg-primary rounded-pill">{{ activity.current_participants }}/{{ activity.max_participants }}</span>
                    </a>
                    {% empty %}
                    <div class="list-group-item text-center text-muted">
                        {% if search_query %}
                        没有找到与 "{{ search_query }}" 相关的附近活动
                        {% else %}
                        暂无附近活动
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 平台特色 - 只在没有搜索时显示 -->
{% if not search_query %}
<section class="py-5 bg-white">
    <div class="container">
        <h2 class="section-title text-center">为什么选择城会玩</h2>
        <div class="row mt-5">
            <div class="col-md-4 text-center mb-4">
                <div class="feature-icon">
                    <i class="fas fa-users"></i>
                </div>
                <h4>社区互动</h4>
                <p class="text-muted">结识志同道合的本地朋友，建立真实的社交关系，丰富你的社交圈。</p>
            </div>
            <div class="col-md-4 text-center mb-4">
                <div class="feature-icon">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                <h4>本地发现</h4>
                <p class="text-muted">探索你身边的有趣活动，无需远行就能体验丰富多彩的本地生活。</p>
            </div>
            <div class="col-md-4 text-center mb-4">
                <div class="feature-icon">
                    <i class="fas fa-calendar-plus"></i>
                </div>
                <h4>轻松创建</h4>
                <p class="text-muted">简单几步即可发起活动，邀请他人参与，成为社区活动的组织者。</p>
            </div>
        </div>
    </div>
</section>
{% endif %}
<script>
    // 地图功能 - 优化版本
    let map = null;
    let markers = [];
    let infoWindows = [];
    let mapLoaded = false;
    let userLocationMarker = null;
    let userLocation = null;

    // 百度地图API密钥
    const BAIDU_MAP_AK = 'cb4Sj7ouHojzu3sHgnpJ6uDUWCPYeV3T';

    // 位置缓存
    const locationCache = {
        key: 'user_location_cache',
        expiry: 5 * 60 * 1000, // 5分钟缓存
        get: function() {
            try {
                const cached = localStorage.getItem(this.key);
                if (!cached) return null;

                const { location, timestamp } = JSON.parse(cached);
                if (Date.now() - timestamp > this.expiry) {
                    localStorage.removeItem(this.key);
                    return null;
                }
                return location;
            } catch (e) {
                return null;
            }
        },
        set: function(location) {
            try {
                const cacheData = {
                    location: location,
                    timestamp: Date.now()
                };
                localStorage.setItem(this.key, JSON.stringify(cacheData));
            } catch (e) {
                // 忽略缓存错误
            }
        }
    };

    // 初始化地图
    function initMap() {
        console.log('开始初始化百度地图...');

        if (mapLoaded) {
            console.log('地图已经初始化过了');
            return;
        }

        try {
            // 检查BMap是否已加载
            if (typeof BMap === 'undefined') {
                console.error('BMap未定义，地图API可能未正确加载');
                showMapError('地图API加载失败，请刷新页面重试');
                return;
            }

            // 创建地图实例
            map = new BMap.Map("map-container");

            // 先检查缓存的位置
            const cachedLocation = locationCache.get();
            let centerPoint;

            if (cachedLocation) {
                centerPoint = new BMap.Point(cachedLocation.lng, cachedLocation.lat);
                console.log('使用缓存位置:', cachedLocation);
            } else {
                // 默认中心点（郑州）
                centerPoint = new BMap.Point(113.665412, 34.757975);
            }

            map.centerAndZoom(centerPoint, cachedLocation ? 14 : 12);

            // 启用滚轮缩放
            map.enableScrollWheelZoom(true);

            // 添加基本控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            map.addControl(new BMap.MapTypeControl());

            console.log('百度地图初始化成功');
            mapLoaded = true;

            // 添加地图控件
            addMapControls();

            // 如果有缓存位置，立即显示附近活动
            if (cachedLocation) {
                const cachedPoint = new BMap.Point(cachedLocation.lng, cachedLocation.lat);
                userLocation = cachedPoint;
                addUserMarker(cachedPoint, false, true); // 标记为缓存位置
                showNearbyActivities(cachedPoint);
            }

            // 异步获取最新位置（不阻塞地图显示）
            setTimeout(() => {
                getUserLocation();
            }, 1000);

        } catch (error) {
            console.error('百度地图初始化失败:', error);
            showMapError('地图初始化失败: ' + error.message);
        }
    }

    // 动态加载百度地图API
    function loadBaiduMap() {
        return new Promise((resolve, reject) => {
            // 检查是否已经加载
            if (typeof BMap !== 'undefined') {
                resolve();
                return;
            }

            const script = document.createElement('script');
            script.src = `https://api.map.baidu.com/api?v=3.0&ak=${BAIDU_MAP_AK}&callback=onBMapLoaded`;
            script.onerror = () => {
                reject(new Error('地图API加载失败，请检查网络连接'));
            };
            document.head.appendChild(script);

            // 设置超时
            setTimeout(() => {
                if (typeof BMap === 'undefined') {
                    reject(new Error('地图API加载超时'));
                }
            }, 10000); // 减少超时时间
        });
    }

    // 百度地图加载完成回调
    window.onBMapLoaded = function() {
        console.log('百度地图API加载完成');
        initMap();
    };

    // 获取用户当前位置 - 优化版本
    function getUserLocation() {
        if (!map) {
            console.error('地图未初始化');
            return;
        }

        // 如果已经有位置了，不再重复获取
        if (userLocation && !isLocationStale()) {
            console.log('已有最新位置，跳过重新获取');
            return;
        }

        const locationLoading = showLocationLoading('正在获取您的位置...');
        console.log('开始获取用户位置...');

        // 设置快速回退机制
        const locationTimeout = setTimeout(() => {
            console.log('精确定位超时，尝试IP定位...');
            useIPLocation();
            locationLoading.remove();
        }, 5000); // 5秒超时

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    clearTimeout(locationTimeout);
                    console.log('获取到精确位置:', position.coords);

                    const userPoint = new BMap.Point(
                        position.coords.longitude,
                        position.coords.latitude
                    );

                    userLocation = userPoint;

                    // 缓存位置
                    locationCache.set({
                        lng: position.coords.longitude,
                        lat: position.coords.latitude
                    });

                    // 平滑移动到用户位置
                    map.panTo(userPoint);
                    map.setZoom(14);

                    // 添加用户位置标记
                    addUserMarker(userPoint);

                    locationLoading.remove();

                    // 显示附近活动
                    showNearbyActivities(userPoint);

                    showLocationSuccess('位置获取成功！正在显示附近活动...');

                },
                function(error) {
                    clearTimeout(locationTimeout);
                    console.warn('获取精确位置失败:', error);

                    let errorMessage = '获取位置失败: ';
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMessage += '用户拒绝了位置请求';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMessage += '位置信息不可用';
                            break;
                        case error.TIMEOUT:
                            errorMessage += '位置请求超时';
                            break;
                        default:
                            errorMessage += '未知错误';
                    }

                    console.log(errorMessage);

                    // 使用IP定位作为备用方案
                    useIPLocation();
                    locationLoading.remove();
                },
                {
                    enableHighAccuracy: true,
                    timeout: 4000, // 减少超时时间
                    maximumAge: 300000 // 5分钟缓存
                }
            );
        } else {
            clearTimeout(locationTimeout);
            console.warn('浏览器不支持地理定位');
            useIPLocation();
            locationLoading.remove();
        }
    }

    // 检查位置是否过时
    function isLocationStale() {
        const cached = locationCache.get();
        return !cached;
    }

    // 使用IP定位
    function useIPLocation() {
        if (!map) return;

        console.log('使用IP定位...');

        const ipLoading = showLocationLoading('正在使用IP定位...');

        const myCity = new BMap.LocalCity();
        myCity.get(function(result) {
            ipLoading.remove();

            console.log('IP定位结果:', result);

            if (result && result.center) {
                const point = new BMap.Point(result.center.lng, result.center.lat);
                userLocation = point;

                // 缓存IP定位结果
                locationCache.set({
                    lng: result.center.lng,
                    lat: result.center.lat
                });

                map.panTo(point);
                map.setZoom(result.level || 12);

                // 添加用户位置标记（IP定位）
                addUserMarker(point, true);

                // 显示附近活动
                showNearbyActivities(point);

                showLocationSuccess('已使用IP定位显示您的大致位置和附近活动');
            } else {
                showLocationError('IP定位失败，将显示默认活动');
                // 即使定位失败，也显示活动
                showAllActivities();
            }
        });
    }

    // 显示附近活动
    function showNearbyActivities(userPoint) {
        if (!map || !userPoint) return;

        console.log('显示附近活动，用户位置:', userPoint);

        const activities = getActivitiesData();
        if (activities.length === 0) {
            console.log('没有活动数据');
            return;
        }

        // 清除之前的标记
        clearActivityMarkers();

        // 计算距离并排序
        const activitiesWithDistance = activities.map(activity => {
            if (activity.latitude && activity.longitude && activity.latitude != 0 && activity.longitude != 0) {
                const activityPoint = new BMap.Point(activity.longitude, activity.latitude);
                const distance = map.getDistance(userPoint, activityPoint);
                return {
                    ...activity,
                    distance: distance,
                    point: activityPoint
                };
            }
            return null;
        }).filter(activity => activity !== null);

        // 按距离排序，只显示最近的10个活动
        activitiesWithDistance.sort((a, b) => a.distance - b.distance);
        const nearbyActivities = activitiesWithDistance.slice(0, 10);

        console.log('附近活动:', nearbyActivities);

        // 添加活动标记
        nearbyActivities.forEach((activity, index) => {
            addActivityMarker(activity, activity.point, index);
        });

        // 更新活动列表显示
        updateActivitiesList(nearbyActivities);

        // 调整地图视野以显示用户位置和附近活动
        adjustMapViewport(userPoint, nearbyActivities);
    }

    // 显示所有活动（定位失败时使用）
    function showAllActivities() {
        const activities = getActivitiesData();
        if (activities.length === 0) return;

        clearActivityMarkers();

        activities.forEach((activity, index) => {
            if (activity.latitude && activity.longitude && activity.latitude != 0 && activity.longitude != 0) {
                const point = new BMap.Point(activity.longitude, activity.latitude);
                addActivityMarker(activity, point, index);
            }
        });

        updateActivitiesList(activities);
        adjustMapViewport();
    }

    // 清除活动标记
    function clearActivityMarkers() {
        markers.forEach(marker => {
            if (marker) map.removeOverlay(marker);
        });
        markers = [];
        infoWindows = [];
    }

    // 更新活动列表显示
    function updateActivitiesList(activities) {
        const listContainer = document.getElementById('nearby-activities-list');
        if (!listContainer) return;

        if (activities.length === 0) {
            listContainer.innerHTML = `
                <div class="list-group-item text-center text-muted">
                    附近暂无活动
                </div>
            `;
            return;
        }

        const listHTML = activities.map(activity => `
            <a href="/meet/active_detail/${activity.id}/"
               class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
               data-activity-id="${activity.id}"
               data-lat="${activity.latitude}"
               data-lng="${activity.longitude}">
                <div>
                    <h6 class="mb-1">${activity.title}</h6>
                    <small class="text-muted">
                        <i class="fas fa-map-marker-alt me-1"></i>
                        ${activity.location_name} ·
                        ${activity.start_time}
                    </small>
                    ${activity.distance ? `
                    <br>
                    <small class="text-info">
                        <i class="fas fa-walking me-1"></i>
                        距离约 ${(activity.distance / 1000).toFixed(1)}公里
                    </small>
                    ` : ''}
                </div>
                <span class="badge bg-primary rounded-pill">${activity.current_participants}/${activity.max_participants}</span>
            </a>
        `).join('');

        listContainer.innerHTML = listHTML;

        // 添加列表项点击事件
        document.querySelectorAll('#nearby-activities-list .list-group-item').forEach(item => {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                const activityId = this.getAttribute('data-activity-id');
                const lat = parseFloat(this.getAttribute('data-lat'));
                const lng = parseFloat(this.getAttribute('data-lng'));

                if (lat && lng) {
                    const point = new BMap.Point(lng, lat);
                    map.panTo(point);
                    map.setZoom(15);

                    // 高亮对应的标记
                    highlightActivityMarker(activityId);
                }

                // 高亮列表项
                document.querySelectorAll('#nearby-activities-list .list-group-item').forEach(item => {
                    item.classList.remove('active');
                });
                this.classList.add('active');
            });
        });
    }

    // 高亮活动标记
    function highlightActivityMarker(activityId) {
        markers.forEach((marker, index) => {
            if (marker && marker.activityId == activityId) {
                marker.openInfoWindow(infoWindows[index]);
            }
        });
    }

    // 调整地图视野
    function adjustMapViewport(userPoint = null, activities = []) {
    if (!map) return;

    const bounds = new BMap.Bounds();

    // 包含用户位置
    if (userPoint) {
        bounds.extend(userPoint);
    }

    // 包含所有活动标记
    markers.forEach(marker => {
        if (marker) bounds.extend(marker.getPosition());
    });

    // 如果没有活动标记，使用默认视野
    if (bounds.isEmpty()) {
        const defaultPoint = new BMap.Point(113.665412, 34.757975);
        map.centerAndZoom(defaultPoint, 12);
    } else {
        // 修复：使用正确的方法设置视野
        map.setViewport(bounds);

        // 如果视野太小（只有一个点），适当缩小
        if (markers.length <= 1 && userPoint) {
            map.setZoom(14);
        }
    }
}

    // 添加用户位置标记
    function addUserMarker(point, isIPLocation = false, isCached = false) {
        if (!map) return;

        // 移除之前的标记
        if (userLocationMarker) {
            map.removeOverlay(userLocationMarker);
        }

        let iconColor, locationType;

        if (isCached) {
            iconColor = '#6c757d'; // 灰色表示缓存位置
            locationType = '您的位置 (缓存)';
        } else if (isIPLocation) {
            iconColor = '#6c757d'; // 灰色表示IP定位
            locationType = '您的大致位置 (IP定位)';
        } else {
            iconColor = '#0078F6'; // 蓝色表示精确定位
            locationType = '您的精确位置';
        }

        const iconSvg = `
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2C7.586 2 4 5.586 4 10C4 14.414 7.586 18 12 18C16.414 18 20 14.414 20 10C20 5.586 16.414 2 12 2ZM12 12C10.897 12 10 11.103 10 10C10 8.897 10.897 8 12 8C13.103 8 14 8.897 14 10C14 11.103 13.103 12 12 12Z" fill="${iconColor}"/>
                <path d="M12 22C7 2 22 7 22 12C22 16.414 18.414 20 14 20C9.586 20 6 16.414 6 12C6 7.586 9.586 4 14 4Z" fill="${iconColor}" fill-opacity="0.1"/>
            </svg>
        `;

        const icon = new BMap.Icon(
            'data:image/svg+xml;base64,' + btoa(iconSvg),
            new BMap.Size(24, 24),
            {
                anchor: new BMap.Size(12, 24)
            }
        );

        userLocationMarker = new BMap.Marker(point, {icon: icon});
        map.addOverlay(userLocationMarker);

        // 添加信息窗口
        const infoWindow = new BMap.InfoWindow(`
            <div style="width: 180px; padding: 8px; font-size: 12px;">
                <strong>${locationType}</strong>
                <br>
                <span>经度: ${point.lng.toFixed(6)}</span>
                <br>
                <span>纬度: ${point.lat.toFixed(6)}</span>
            </div>
        `);

        userLocationMarker.addEventListener('click', function() {
            this.openInfoWindow(infoWindow);
        });
    }

    // 添加单个活动标记
    function addActivityMarker(activity, point, index) {
        // 创建自定义活动图标
        const activityIcon = new BMap.Icon(
            '',
            new BMap.Size(24, 24),
            {
                anchor: new BMap.Size(12, 24)
            }
        );

        const marker = new BMap.Marker(point, {icon: activityIcon});
        marker.activityId = activity.id; // 存储活动ID
        map.addOverlay(marker);
        markers.push(marker);

        // 创建信息窗口内容
        const distanceInfo = activity.distance ?
            `<p style="margin: 0 0 5px 0; font-size: 12px; color: #666;">
                <i class="fas fa-walking" style="color: #FF6B35;"></i>
                距离约 ${(activity.distance / 1000).toFixed(1)}公里
            </p>` : '';

        const content = `
            <div style="width: 280px; padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                <h6 style="margin: 0 0 8px 0; color: #FF6B35; font-size: 14px; font-weight: 600;">${activity.title}</h6>
                <p style="margin: 0 0 5px 0; font-size: 12px; color: #666;">
                    <i class="fas fa-map-marker-alt" style="color: #FF6B35;"></i> ${activity.location_name}
                </p>
                <p style="margin: 0 0 5px 0; font-size: 12px; color: #666;">
                    <i class="far fa-calendar-alt" style="color: #FF6B35;"></i> ${activity.start_time}
                </p>
                ${distanceInfo}
                <p style="margin: 0 0 8px 0; font-size: 12px; color: #666;">
                    <i class="fas fa-users" style="color: #FF6B35;"></i> ${activity.current_participants}/${activity.max_participants}人
                    ${activity.is_full ? '<span style="color: #dc3545; font-weight: 600;">(已满员)</span>' : ''}
                </p>
                <a href="/meet/active_detail/${activity.id}/"
                   style="font-size: 12px; padding: 4px 12px; text-decoration: none; background: #FF6B35; border: none; border-radius: 4px; color: white; display: inline-block;">
                    查看详情
                </a>
            </div>
        `;

        const infoWindow = new BMap.InfoWindow(content);
        infoWindows.push(infoWindow);

        marker.addEventListener('click', function() {
            this.openInfoWindow(infoWindow);
            highlightActivityListItem(activity.id);
        });
    }

    // 高亮对应的列表项
    function highlightActivityListItem(activityId) {
        document.querySelectorAll('#nearby-activities-list .list-group-item').forEach(item => {
            item.classList.remove('active');
        });

        const targetItem = document.querySelector(`[data-activity-id="${activityId}"]`);
        if (targetItem) {
            targetItem.classList.add('active');
            targetItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }

    // 获取活动数据
    function getActivitiesData() {
        return [
            {% for activity in nearby_activities %}
            {
                id: {{ activity.id }},
                title: "{{ activity.title|escapejs }}",
                location_name: "{{ activity.location_name|escapejs }}",
                latitude: {{ activity.latitude|default:0 }},
                longitude: {{ activity.longitude|default:0 }},
                current_participants: {{ activity.current_participants }},
                max_participants: {{ activity.max_participants }},
                start_time: "{{ activity.start_time|date:'m月d日 H:i' }}",
                is_full: {% if activity.is_full %}true{% else %}false{% endif %}
            }{% if not forloop.last %},{% endif %}
            {% endfor %}
        ];
    }

    // 显示定位加载状态
    function showLocationLoading(message = '正在获取您的位置...') {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'location-loading';
        loadingDiv.innerHTML = `
            <div class="spinner-border text-primary" role="status" style="width: 1.5rem; height: 1.5rem;">
                <span class="visually-hidden">加载中...</span>
            </div>
            <div class="loading-text">${message}</div>
        `;
        document.getElementById('map-container').appendChild(loadingDiv);
        return loadingDiv;
    }

    // 显示定位成功提示
    function showLocationSuccess(message) {
        const successDiv = document.createElement('div');
        successDiv.className = 'location-loading';
        successDiv.innerHTML = `
            <div class="text-success">
                <i class="fas fa-check-circle fa-2x mb-2"></i>
                <div class="loading-text">${message}</div>
            </div>
        `;
        document.getElementById('map-container').appendChild(successDiv);

        // 2秒后自动移除
        setTimeout(() => {
            successDiv.remove();
        }, 2000);
    }

    // 显示定位错误提示
    function showLocationError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'location-loading';
        errorDiv.innerHTML = `
            <div class="text-warning">
                <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                <div class="loading-text">${message}</div>
                <button class="btn btn-primary btn-sm mt-2" onclick="getUserLocation()">
                    <i class="fas fa-redo"></i> 重试定位
                </button>
            </div>
        `;
        document.getElementById('map-container').appendChild(errorDiv);

        // 5秒后自动移除
        setTimeout(() => {
            errorDiv.remove();
        }, 5000);
    }

    // 显示地图错误
    function showMapError(message) {
        const mapContainer = document.getElementById('map-container');
        mapContainer.innerHTML = `
            <div class="map-error">
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle fa-3x mb-3 text-warning"></i>
                    <h5>地图加载失败</h5>
                    <p class="small text-muted">${message || '请检查网络连接或稍后重试'}</p>
                    <button class="btn btn-primary btn-sm" onclick="retryMapLoad()">
                        <i class="fas fa-redo"></i> 重新加载地图
                    </button>
                </div>
            </div>
        `;
    }

    // 重新加载地图
    function retryMapLoad() {
        mapLoaded = false;
        loadBaiduMap().catch(error => {
            console.error('重新加载地图失败:', error);
            showMapError('地图加载失败: ' + error.message);
        });
    }

    // 添加地图控件
    function addMapControls() {
        if (!map) return;

        const controlsDiv = document.createElement('div');
        controlsDiv.className = 'map-controls';

        const locationBtn = document.createElement('button');
        locationBtn.className = 'btn btn-light btn-sm';
        locationBtn.innerHTML = '<i class="fas fa-location-arrow"></i>';
        locationBtn.title = '定位到我的位置';
        locationBtn.onclick = getUserLocation;

        const refreshBtn = document.createElement('button');
        refreshBtn.className = 'btn btn-light btn-sm';
        refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i>';
        refreshBtn.title = '刷新活动';
        refreshBtn.onclick = function() {
            if (userLocation) {
                showNearbyActivities(userLocation);
            } else {
                getUserLocation();
            }
        };

        controlsDiv.appendChild(locationBtn);
        controlsDiv.appendChild(refreshBtn);

        document.getElementById('map-container').appendChild(controlsDiv);
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('页面加载完成，开始加载地图...');

        // 立即开始加载地图，不延迟
        loadBaiduMap().catch(error => {
            console.error('地图加载失败:', error);
            showMapError('地图加载失败: ' + error.message);
        });
    });
</script>
{% endblock %}